/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.dataModel.service;

import com.fzhucc.modules.dataCg.domain.DataCg;
import com.fzhucc.modules.dataCg.repository.DataCgRepository;
import com.fzhucc.modules.dataLls.domain.DataLls;
import com.fzhucc.modules.dataLls.repository.DataLlsRepository;
import com.fzhucc.modules.dataModel.domain.DataModel;
import com.fzhucc.modules.dataOrg.domain.DataOrg;
import com.fzhucc.modules.dataOrg.repository.DataOrgRepository;
import com.fzhucc.modules.dataStudio.domain.DataStudio;
import com.fzhucc.modules.dataStudio.repository.DataStudioRepository;
import com.fzhucc.modules.dataTs.domain.DataTs;
import com.fzhucc.modules.dataTs.repository.DataTsRepository;
import com.fzhucc.modules.dataXq.domain.DataXq;
import com.fzhucc.modules.dataXq.repository.DataXqRepository;
import com.fzhucc.modules.dataZcs.domain.DataZcs;
import com.fzhucc.modules.dataZcs.repository.DataZcsRepository;
import com.fzhucc.modules.dataZx.domain.DataZx;
import com.fzhucc.modules.dataZx.repository.DataZxRepository;
import com.fzhucc.modules.hot.domain.HotRecord;
import com.fzhucc.modules.hot.repository.HotRecordRepository;
import com.fzhucc.modules.notice.repository.NoticeRepository;
import com.fzhucc.modules.pms.repository.ProjectRepository;
import com.fzhucc.modules.sciPersonnelInfo.repository.SciPersonnelInfoRepository;
import com.fzhucc.modules.sciStudio.repository.SciStudioRepository;
import com.fzhucc.modules.sciTechnologyDemand.repository.SciTechnologyDemandRepository;
import com.fzhucc.modules.sciTechnologyDemand.service.mapstruct.SciTechnologyDemandMapper;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.ts.repository.TsTeamRepository;
import com.fzhucc.utils.ValidationUtil;
import com.fzhucc.utils.FileUtil;
import com.fzhucc.utils.PageUtil;
import com.fzhucc.utils.QueryHelp;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.dataModel.repository.DataModelRepository;
import com.fzhucc.modules.dataModel.domain.dto.DataModelDto;
import com.fzhucc.modules.dataModel.domain.dto.DataModelQueryCriteria;
import com.fzhucc.modules.dataModel.service.mapstruct.DataModelMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-03-29
 **/
@Service
@RequiredArgsConstructor
public class DataModelService {

    private final DataModelRepository dataModelRepository;

    private final HotRecordRepository hotRecordRepository;

    private final DataCgRepository dataCgRepository;

    private final DataLlsRepository dataLlsRepository;

    private final DataStudioRepository dataStudioRepository;

    private final DataTsRepository dataTsRepository;

    private final DataXqRepository dataXqRepository;

    private final DataZxRepository dataZxRepository;
    private final DataModelMapper dataModelMapper;

    private final DataZcsRepository dataZcsRepository;

    private final ProjectRepository projectRepository;

    private final SciTechnologyDemandRepository sciTechnologyDemandRepository;

    private final SciPersonnelInfoRepository sciPersonnelInfoRepository;

    private final TsTeamRepository tsTeamRepository;

    private final SciStudioRepository sciStudioRepository;

    private final NoticeRepository noticeRepository;

    private final DataOrgRepository dataOrgRepository;

    private final UserRepository userRepository;

    @Value("${sci.audit.shtg}")
    public String shtg;


    public Map<String, Object> queryAll(DataModelQueryCriteria criteria, Pageable pageable) {
        Page<DataModel> page = dataModelRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(dataModelMapper::toDto));
    }

    public List<DataModelDto> queryAll(DataModelQueryCriteria criteria) {
        return dataModelMapper.toDto(dataModelRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Transactional
    public DataModelDto findById(Integer id) {
        DataModel dataModel = dataModelRepository.findById(id).orElseGet(DataModel::new);
        ValidationUtil.isNull(dataModel.getId(), "DataModel", "id", id);
        return dataModelMapper.toDto(dataModel);
    }

    @Transactional(rollbackFor = Exception.class)
    public DataModelDto create(DataModel resources) {
        return dataModelMapper.toDto(dataModelRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(DataModel resources) {
        DataModel dataModel = dataModelRepository.findById(resources.getId()).orElseGet(DataModel::new);
        ValidationUtil.isNull(dataModel.getId(), "DataModel", "id", resources.getId());
        dataModel.copy(resources);
        dataModelRepository.save(dataModel);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            dataModelRepository.deleteById(id);
        }
    }

    public void download(List<DataModelDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DataModelDto dataModel : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("值", dataModel.getValue());
            map.put("日期", dataModel.getDay());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public void doSaveBigData() {
        List<DataOrg> all = dataOrgRepository.findAll();
        if (all!=null && all.size()>0){
            for (DataOrg org:all){
                scaleValue(org.getOrg());
            }
        }
    }

    public void scaleValue(String orgArea) {
        String[] split = orgArea.split(";");

        int zx = 0; //资讯
        int cxgzs = 0; //创新工作室
        int lmgjfwd = 0; //劳模工匠服务队
        int cxcgs = 0; //创新成果数
        int lmgjs = 0; //劳模工匠数
        int qyxqs = 0; //企业需求数
        int lls = 0; //浏览量
        int zcs = 0; //注册数
        String str = "";

        if (split.length == 1) {
            //直接拿去like
            str = split[0];
        } else if (split.length == 2) {
            //拿第第一个拼第二个去like
            str = split[0] + ";" + split[1];
        } else if (split.length == 3) {
            //拿第一个拼第二个拼第三个去like
            str = split[0] + ";" + split[1] + ";" + split[2];
        }
        String lastStr = str;
        str = "%" + str + "%";


        lmgjs = sciPersonnelInfoRepository.findCountNormalByLikeArea(str, shtg);
        qyxqs = sciTechnologyDemandRepository.findCountNormalByLikeArea(str, shtg);
        if (str.contains("福州") || str.contains("福建")) {
            cxcgs = projectRepository.findCountNormalByLikeArea("%福州市%");
        } else {
            cxcgs = projectRepository.findCountNormalByLikeArea(str);
        }
        cxgzs = sciStudioRepository.findCountNormalByLikeArea(str, shtg);
        lmgjfwd = tsTeamRepository.findCountNormalByLikeArea(str, shtg);
        zx = noticeRepository.findCountNormalByLikeArea(str);
        zcs = userRepository.findCountNormalByLikeArea(str);//注册数
        if (str.equals("%福建省;福州市%") || str.equals("%福建省%")||  str.equals("%福建省;%")){
            zcs = zcs + 1800 ; //福建省 福州市额外加1800
        }

        if (lastStr.equals("福建省;") || lastStr.equals("福建省")) {
            lls = hotRecordRepository.findAllCounts();//浏览量
            lls = lls + 14000; //浏览量额外增加14000
        } else if (lastStr.equals("福建省;福州市;") || lastStr.equals("福建省;福州市")) {
            lls = hotRecordRepository.findCountNormalByLikeArea("%福州%");//浏览量
            lls = lls + 14000; //浏览量额外增加14000
        } else if (lastStr.contains("福建省;莆田市;") || lastStr.contains("福建省;莆田市")) {
            lls = hotRecordRepository.findCountNormalByLikeArea("%莆田%");//浏览量
        } else if (lastStr.contains("福建省;泉州市;") || lastStr.contains("福建省;泉州市")) {
            lls = hotRecordRepository.findCountNormalByLikeArea("%泉州%");//浏览量
        } else if (lastStr.contains("福建省;厦门市;") || lastStr.contains("福建省;厦门市")) {
            lls = hotRecordRepository.findCountNormalByLikeArea("%厦门%");//浏览量
        } else if (lastStr.contains("福建省;漳州市;") || lastStr.contains("福建省;漳州市")) {
            lls = hotRecordRepository.findCountNormalByLikeArea("%漳州%");//浏览量
        } else if (lastStr.contains("福建省;龙岩市;") || lastStr.contains("福建省;龙岩市")) {
            lls = hotRecordRepository.findCountNormalByLikeArea("%龙岩%");//浏览量
        } else if (lastStr.contains("福建省;三明市;") || lastStr.contains("福建省;三明市")) {
            lls = hotRecordRepository.findCountNormalByLikeArea("%三明%");//浏览量
        } else if (lastStr.contains("福建省;南平市;") || lastStr.contains("福建省;南平市")) {
            lls = hotRecordRepository.findCountNormalByLikeArea("%南平%");//浏览量
        } else if (lastStr.contains("福建省;宁德市;") || lastStr.contains("福建省;宁德市")) {
            lls = hotRecordRepository.findCountNormalByLikeArea("%宁德%");//浏览量
        } else if (lastStr.contains("福建省;平潭综合实验区;") || lastStr.contains("福建省;平潭综合实验区")) {
            lls = hotRecordRepository.findCountNormalByLikeArea("%平潭%");//浏览量
        } else {
            lls = 0;
        }




        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取前一天
        LocalDate yesterday = today.minusDays(1);
        // 格式化日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = yesterday.format(formatter);


        DataModel dataModel = new DataModel();
        DataCg dataCg = new DataCg();
        DataStudio dataStudio = new DataStudio();
        DataTs dataTs = new DataTs();
        DataXq dataXq = new DataXq();
        DataZx dataZx = new DataZx();
        DataLls dataLls = new DataLls();
        DataZcs dataZcs = new DataZcs();

        dataModel.setDay(formattedDate);
        dataModel.setOrgArea(orgArea);
        dataModel.setValue(lmgjs);
        dataModel.setMytime(yesterday);

        dataCg.setDay(formattedDate);
        dataCg.setOrgArea(orgArea);
        dataCg.setValue(cxcgs);
        dataCg.setMytime(yesterday);

        dataStudio.setDay(formattedDate);
        dataStudio.setOrgArea(orgArea);
        dataStudio.setValue(cxgzs);
        dataStudio.setMytime(yesterday);

        dataTs.setDay(formattedDate);
        dataTs.setOrgArea(orgArea);
        dataTs.setValue(lmgjfwd);
        dataTs.setMytime(yesterday);

        dataXq.setDay(formattedDate);
        dataXq.setOrgArea(orgArea);
        dataXq.setValue(qyxqs);
        dataXq.setMytime(yesterday);

        dataZx.setDay(formattedDate);
        dataZx.setOrgArea(orgArea);
        dataZx.setValue(zx);
        dataZx.setMytime(yesterday);

        dataLls.setDay(formattedDate);
        dataLls.setOrgArea(orgArea);
        dataLls.setValue(lls);
        dataLls.setMytime(yesterday);

        dataZcs.setDay(formattedDate);
        dataZcs.setOrgArea(orgArea);
        dataZcs.setValue(zcs);
        dataZcs.setMytime(yesterday);

        dataModelRepository.save(dataModel);
        dataCgRepository.save(dataCg);
        dataStudioRepository.save(dataStudio);
        dataTsRepository.save(dataTs);
        dataXqRepository.save(dataXq);
        dataZxRepository.save(dataZx);
        dataLlsRepository.save(dataLls);
        dataZcsRepository.save(dataZcs);
    }
}